package com.hrg.rds.biz.runner;

import com.hrg.rds.biz.comm.PushService;
import com.hrg.rds.biz.config.RdsConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ConfigPushRunner implements CommandLineRunner {
	// 若该方法抛出异常，Spring Boot 会将其视为启动失败，进而停止应用。
	private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
	@Override
	public void run(String... args) {
		Runnable runnable = () -> RdsConfiguration.AgvIpMap.forEach((ip, agvVo) -> {
			if (agvVo.isIfConnectActive() && !agvVo.isIfConfigPushSuccess()) {
				log.debug("配置推送开始");
				boolean success = PushService.pushConfig(agvVo.getIp());
				if (success) {
					agvVo.setIfConfigPushSuccess(true);
				}
				log.debug("配置推送success={}", success);
			}
		});
		executorService.scheduleWithFixedDelay(runnable, 0, 1, TimeUnit.SECONDS);
	}
}
